<template>
	<div class="regulation-list-page">
		<!-- 搜索栏 -->
		<van-search v-model="searchValue" placeholder="请输入相关信息搜索" @search="onSearch" @clear="onClear" />

		<!-- 列表加载状态 -->
		<div v-if="loading && regulationList.length === 0" class="loading-container">
			<van-loading type="spinner" color="#1989fa" vertical> 加载中... </van-loading>
		</div>

		<!-- 法规列表 -->
		<div class="regulation-list">
			<div v-for="item in regulationList" :key="item.id" class="regulation-card" @click="goToDetail(item)">
				<!-- 封面图 -->
				<div class="card-image">
					<img v-if="item.imgUrl" :src="item.imgUrl" alt="封面" />
					<div v-else class="placeholder-image">
						<van-icon name="description" size="40" color="#dcdee0" />
					</div>
				</div>

				<!-- 内容信息 -->
				<div class="card-content">
					<div class="card-title">{{ item.docName }}</div>
					<div class="card-footer">
						<span class="date-text">
							<van-icon name="clock-o" size="14" />
							{{ formatDate(item.releaseDate) }}
						</span>
					</div>
				</div>

				<!-- 箭头 -->
				<div class="card-arrow">
					<van-icon name="arrow" color="#c8c9cc" />
				</div>
			</div>
		</div>

		<!-- 加载更多 -->
		<div v-if="loading && regulationList.length > 0" class="loading-more">
			<van-loading type="spinner" size="20" color="#1989fa"> 加载中... </van-loading>
		</div>

		<!-- 底部提示 -->
		<van-divider v-if="regulationList.length >= total && hasScrolled && !loading && total > 0" content-position="center">
			我也是有底线的
		</van-divider>

		<!-- 空状态 -->
		<van-empty v-if="!loading && regulationList.length === 0" description="暂无法规数据" />
	</div>
</template>

<script>
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { getRegulationList } from '@/api/regulation'
import { useUserStore } from '@/stores/user'

/**
 * 法律法规列表页面
 * 注意：此页面为公开访问，不需要登录/token验证，游客可直接访问
 */
export default {
	name: 'RegulationList',
	setup() {
		const router = useRouter()
		const userStore = useUserStore()

		// 响应式数据
		const loading = ref(false)
		const regulationList = ref([])
		const searchValue = ref('')
		const total = ref(0)
		const hasScrolled = ref(false)

		// 分页参数
		const pageNum = ref(1)
		const pageSize = ref(10)
		const pages = ref(0)

		// 格式化日期
		const formatDate = (dateStr) => {
			if (!dateStr) return ''
			const date = new Date(dateStr)
			const year = date.getFullYear()
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			return `${year}-${month}-${day}`
		}

		// 搜索
		const onSearch = () => {
			loadRegulationList(true)
		}

		// 清空搜索
		const onClear = () => {
			searchValue.value = ''
			loadRegulationList(true)
		}

		// 跳转到详情页或直接打开PDF
		const goToDetail = (item) => {
			console.log('点击法规项:', item)

			if (!item.accessUrl) {
				showToast('该法规文档链接不存在')
				return
			}

			// 判断用户登录状态
			const isAuthenticated = userStore.isAuthenticated
			console.log('用户登录状态:', isAuthenticated ? '已登录' : '游客')

			if (!isAuthenticated) {
				// 游客状态：跳转到详情页面
				console.log('游客状态，跳转到详情页面')
				router.push({
					path: '/regulation/detail',
					query: {
						id: item.id,
					},
				})
			} else {
				// 非游客状态（已登录）：直接在新标签页打开PDF
				console.log('已登录状态，在新标签页打开PDF:', item.accessUrl)
				window.open(item.accessUrl, '_blank')
			}
		}

		// 加载法规列表
		const loadRegulationList = async (isRefresh = false) => {
			if (isRefresh) {
				pageNum.value = 1
				regulationList.value = []
				hasScrolled.value = false
			}

			loading.value = true

			try {
				const params = {
					pageNum: pageNum.value,
					pageSize: pageSize.value,
				}

				// 添加搜索条件
				if (searchValue.value) {
					params.docName = searchValue.value
				}

				const response = await getRegulationList(params)

				if (response.code === '0') {
					const currentList = isRefresh ? [] : regulationList.value
					const rows = response.rows || []

					regulationList.value = currentList.concat(rows)
					pages.value = response.pages || 0
					total.value = response.total || 0
				} else {
					showToast(response.msg || '获取法规列表失败')
				}
			} catch (error) {
				console.error('获取法规列表失败:', error)
				showToast('网络错误，请稍后重试')
			} finally {
				loading.value = false
			}
		}

		// 上拉加载更多
		const onReachBottom = () => {
			const nextPage = pageNum.value + 1
			if (nextPage > pages.value || loading.value) return

			pageNum.value = nextPage
			hasScrolled.value = true
			loadRegulationList()
		}

		// 监听滚动事件
		const handleScroll = () => {
			const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
			const windowHeight = window.innerHeight
			const scrollHeight = document.documentElement.scrollHeight

			// 距离底部50px时触发加载
			if (scrollTop + windowHeight >= scrollHeight - 50) {
				onReachBottom()
			}
		}

		onMounted(() => {
			loadRegulationList(true)
			// 添加滚动监听
			window.addEventListener('scroll', handleScroll)
		})

		// 组件卸载时移除监听
		const onUnmounted = () => {
			window.removeEventListener('scroll', handleScroll)
		}

		return {
			loading,
			regulationList,
			searchValue,
			total,
			hasScrolled,
			formatDate,
			onSearch,
			onClear,
			goToDetail,
			onReachBottom,
		}
	},
}
</script>

<style lang="less" scoped>
.regulation-list-page {
	background-color: #f7f8fa;
	min-height: 100vh;
	padding-bottom: 20px;
}

.loading-container {
	position: fixed;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	z-index: 1000;
}

.loading-more {
	text-align: center;
	padding: 16px 0;
}

.regulation-list {
	padding: 0 16px;
}

.regulation-card {
	background: #fff;
	border-radius: 8px;
	margin-bottom: 12px;
	padding: 12px;
	display: flex;
	align-items: center;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
	cursor: pointer;
	transition: all 0.3s ease;

	&:active {
		transform: scale(0.98);
		background: #f8f8f8;
	}

	.card-image {
		width: 80px;
		height: 80px;
		border-radius: 4px;
		overflow: hidden;
		flex-shrink: 0;
		background: #f7f8fa;
		display: flex;
		align-items: center;
		justify-content: center;

		img {
			width: 100%;
			height: 100%;
			object-fit: cover;
		}

		.placeholder-image {
			width: 100%;
			height: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
			background: #f0f0f0;
		}
	}

	.card-content {
		flex: 1;
		padding: 0 12px;
		min-width: 0;

		.card-title {
			font-size: 15px;
			font-weight: 500;
			color: #323233;
			line-height: 22px;
			margin-bottom: 8px;
			display: -webkit-box;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 2;
			line-clamp: 2;
			overflow: hidden;
			text-overflow: ellipsis;
		}

		.card-footer {
			.date-text {
				font-size: 12px;
				color: #969799;
				display: flex;
				align-items: center;
				gap: 4px;
			}
		}
	}

	.card-arrow {
		flex-shrink: 0;
	}
}

:deep(.van-search) {
	padding: 10px 16px;
}
</style>
